/*
如何使用：
  在对应页面的js中最上方引入const common = require('/utils/common.js');
  然后使用的时候是var data = await common.post(xxx,{aaa:aaa,bbb:bbb});
*/
/**
 * 调用微信的登录接口，获取随机码code
 */
var urls = require("../utils/urls");
var tip = require("../utils/tip");
let count = 0;
let globalData = {
  unRequest: null
}

export function wxLogin() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success(res) {
        resolve(res)
      },
      fail(res) {
        reject(res);
      }
    });
  })
}

//单参数回调
export function callbackOne(cb, param) {
  if (cb != undefined && cb != null) {
    cb(param);
  }
}

//双参数回调
export function callbackTwo(cb, param1, param2) {
  if (cb != undefined && cb != null) {
    cb(param1, param2);
  }
}

export async function getLeaderAsync(app, cb) {
  var that = this;
  var leader = await that.getLeader(app);
  that.callbackOne(cb, leader);
}

/**
 * 获取用户手机号
 * @param {} app app对象
 */
export async function getUserPhone(app) {
  var that = this;
  if (that.isBlank(app)) {
    console.error("get openid error, app is null or undefined");
    return null;
  }
  // 从全局数据中读取
  var userPhone = app.globalData.userPhone;
  if (!that.isBlank(userPhone)) {
    // console.log("app global data userPhone");
    return userPhone;
  }
  // 全局数据中没有，尝试从缓存中读取
  userPhone = wx.getStorageSync('userPhone');
  if (!that.isBlank(userPhone)) {
    app.globalData.userPhone = userPhone;
    // console.log("缓存获取到的手机号：",userPhone);
    return userPhone;
  }
  // 全局数据和缓存中没有，重新获取
  return await that.getNewUserPhone(app);
}

export function isLogin(app) {
  var that = this;
  var userInfo = that.getUserInfo(app);
  return !that.isBlank(userInfo);
}

export function getUserInfo(app) {
  var that = this;
  if (that.isBlank(app)) {
    console.error("get userinfo error, app is null or undefined");
    return {};
  }
  // 从全局数据中读取
  var userInfo = app.globalData.userInfo;
  if (!that.isBlank(userInfo)) {
    // console.log("app global data userInfo");
    return userInfo;
  }
  // 全局数据中没有，尝试从缓存中读取
  userInfo = wx.getStorageSync('userInfo');
  if (!that.isBlank(userInfo)) {
    app.globalData.userInfo = userInfo;
    // console.log("storage sync userInfo");
    return userInfo;
  }
  // 全局数据和缓存中没有，目前可能未登录
  // console.log("can not get user info, maybe not login");
  return {};
}

/**
 * 用户授权登录
 * @param {} app app对象
 * @param {} data 点击数据
 */
export async function login(app, data, cb) {
  let that = this;
  var openId = await that.getOpenId(app);
  var errMsg = "未知错误";
  var success = false;
  try {
    // 判断用户是否授权
    if (data.detail.rawData) {
      wx.getSetting({
        success: (data) => {
          if (data.authSetting["scope.userInfo"]) {
            //用户已经授权
            console.log("用户已经授权");
            //加载用户信息
            wx.getUserInfo({
              success: (data) => {
                console.log("加载用户信息");
                var userInfo = data.userInfo;
                console.log("加载用户信息" + userinfo);
                //设置到全局变量中
                app.globalData.userInfo = userInfo;
                //设置到缓存中去
                wx.setStorageSync('userInfo', userInfo);
              },
              fail: (res) => {
                errMsg = "获取用户信息失败";
                console.log(errMsg);
                that.callbackTwo(cb, success, errMsg);
              }
            })
          } else {
            errMsg = "用户未授权";
            console.log(errMsg);
            that.callbackTwo(cb, success, errMsg);
          }
        }
      });
    } else {
      errMsg = "用户未授权登录"
      console.log(errMsg);
      that.callbackTwo(cb, success, errMsg);
    }
  } catch (e) {
    errMsg = "获取用户信息失败"
    console.log(errMsg);
    that.callbackTwo(cb, success, errMsg);
  }
}

/**
 * 用户注销，清除缓存和全局数据
 * @param {} app app对象
 */
export function logout(app) {
  // 登出的时候先将购物车选中缓存取出
  let cartSelectCache = wx.getStorageSync('cartSelectCache');
  wx.clearStorageSync();
  wx.clearStorage();
}

/**
 * 判断对象是否为空
 */
export function isBlank(str) {
  if (str == undefined || str == null) {
    return true;
  }
  if (Object.prototype.toString.call(str) === '[object Undefined]') { //空
    return true
  } else if (
    Object.prototype.toString.call(str) === '[object String]' ||
    Object.prototype.toString.call(str) === '[object Array]') { //字条串或数组
    return str.length == 0 ? true : false
  } else if (Object.prototype.toString.call(str) === '[object Object]') {
    return JSON.stringify(str) == '{}' ? true : false
  } else {
    return true
  }
}

export function objNotNull(obj) {
  if (null === obj || undefined === obj || "" === obj) {
    return false
  } else if (Object.keys(obj).length === 0) {
    return false // 如果为空,返回false
  } else {
    return true // 如果不为空，则会执行到这一步，返回true
  }
}

// 验证手机号码是否有效
export function isPhoneAvailable(phone) {
  var length = phone.length;
  if (length == 11 && (/^1(1|2|3|4|5|6|7|8|9)\d{9}$/.test(phone))) {
    return true;
  } else {
    return false;
  }
}

export function goIndex() {
  wx.switchTab({
    url: '/pages/index/index',
  })
}

/**
 * 第一种使用方法
 * 一、以下是方法的异步调用
 *
 *  Async - 定义异步函数(export async function someName(){...})
 1、自动把函数转换为 Promise
 2、当调用异步函数时，函数返回值会被 resolve 处理
 3、异步函数内部可以使用 await
 Await - 暂停异步函数的执行 (var result = await someAsyncCall();)
 1、当使用在 Promise 前面时，await 等待 Promise 完成，并返回 Promise 的结果
 2、await 只能和 Promise 一起使用，不能和 callback 一起使用
 3、await 只能用在 async 函数中

 二、同步调用函数
 async testAsync() {
            let that=this;
            let data=await get(url,data);//此时就可以获取到同步请求的数据了（post也是如此）
        },
 第二种使用方法
 * 方法的调用common.get().then((res) => { console.log(res) }).catch((res) => { console.log(res) })
 * @param {*} url  请求地址
 * @param {*} data  入参
 */
export function get(url, data) {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: "GET",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Blade-Auth': getToken()
      },
      success: function (res) {
        console.log(res, 'res.data00000000000')
        if (res.data.code == 200) {
          count = 0;
          resolve(res.data);
          return
        }


        if (res.data.code == 401) {
          console.log(count, '哈哈')
          tip.showToast('登录已过期,请重新登录', 'error', 1000)
          setTimeout(() => {
            tip.pageDelayJump("/pages/login/login", null, 1000);
          }, 1000)
          // if (count > 0) {
          // tip.pageDelayJump("../pages/login/login", null, 1000);
          // }
          // updateToken();
          // globalData.unRequest = function () {
          //   resolve(self.get(url, data))
          // }
          return
        }
        reject(res)
      },
      fail: function (res) {
        // console.error(res)
        reject(res)
      }
    })
  })
}

export function getLimit(url, data) {
  if (!data.current) {
    data.current = 1
  }
  if (!data.size) {
    data.size = 10
  }
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: "GET",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Blade-Auth': getToken()
      },
      success: function (res) {
        if (res.data.code == 200) {
          count = 0;
          resolve(res.data);
        }
        if (res.data.code == 401) {
          if (count > 0) {
            tip.pageDelayJump("../pages/login/phone/phone", null, 1000);
          }
          updateToken();
          globalData.unRequest = function () {
            resolve(self.get(url, data))
          }
        }
      },
      fail: function (res) {
        console.error(res)
        reject(res)
      }
    })
  })
}

/**
 * @param {*} url  请求地址
 * @param {*} data  入参
 */
export function post(url, data) {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Blade-Auth': getToken()
      },
      success: function (res) {
        if (res.data.code == 200) {
          count = 0;
          resolve(res.data);
          return
        }
        if (res.data.code == 401) {
          if (count > 0) {
            wx.navigateTo({
              url: '../../login/phone/phone',
            })
            // tip.pageDelayJump("../pages/login/phone/phone", null, 1000);
          }
          updateToken();
          globalData.unRequest = function () {
            resolve(self.post(url, data))
          }
          return
        }
        reject(res.data);
      },
      fail: function (res) {
        reject(res.data);
      },
    });
  })
}

export function postJson(url, data) {
  let self = this;
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: "POST",
      header: {
        'content-type': 'application/json',
        'authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
        'Blade-Auth': getToken()
      },
      success: function (res) {
        if (res.data.code == 200) {
          count = 0;
          resolve(res.data);
        }

        if (res.data.code == 401) {
          tip.showToast('登录已过期,请重新登录', 'error', 1000)
          setTimeout(() => {
            tip.pageDelayJump("/pages/login/login", null, 1000);
          }, 1000)

          // console.log(count,'count0000000000')
          // if (count > 0) {
          // wx.navigateTo({
          //   url: '../pages/login/login',
          // })
          // }
          // updateToken();
          // globalData.unRequest = function () {
          //   resolve(self.postJson(url, data))
          // }
        }
        //如果是其他状态值(需要单独方法里面处理)
        if (res.data.code != 200 && res.data.code != 401) {
          count = 0;
          resolve(res.data);
        }
      },
      fail: function (res) {
        reject(res.data);
      },
    });
  })
}

export function postFormData(url, data) {
  let self = this;
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: "POST",//17793839031
      header: {
        "Content-Type": "multipart/form-data",
        'Blade-Auth': getToken()
      },
      // header: {
      //   'content-type': 'multipart/form-data',
      //   // 'authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
      //   'Blade-Auth': getToken()
      // },
      success: function (res) {
        if (res.data.code == 200) {
          count = 0;
          resolve(res.data);
        }
        // if (res.data.code == 401) {
        //   if (count > 0) {
        //     wx.navigateTo({
        //       url: '../../login/phone/phone',
        //     })
        //   }
        //   updateToken();
        //   globalData.unRequest = function () {
        //     resolve(self.postJson(url, data))
        //   }
        // }
        //如果是其他状态值(需要单独方法里面处理)
        if (res.data.code != 200 && res.data.code != 401) {
          count = 0;
          resolve(res.data);
        }
      },
      fail: function (res) {
        reject(res.data);
      },
    });
  })
}

export function putJson(url, data) {
  let self = this;
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: 'PUT',
      header: {
        'content-type': 'application/json',
        'authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
        'Blade-Auth': getToken()
      },
      success: function (res) {
        if (res.data.code == 200) {
          count = 0;
          resolve(res.data);
        }
        if (res.data.code == 401) {
          if (count > 0) {
            tip.pageDelayJump("../pages/login/phone/phone", null, 1000);
          }
          updateToken();
          globalData.unRequest = function () {
            resolve(self.postJson(url, data))
          }
        }
        if (res.data.code != 200 && res.data.code != 401) {
          tip.showToast(res.data.msg, 'error', 1000)
        }
      },
      fail: function (res) {
        reject(res.data);
      },
    })
  })
}

export function deleteForm(url, data) {
  let self = this;
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: 'DELETE',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
        'Blade-Auth': getToken()
      },
      success: function (res) {
        if (res.data.code == 200) {
          count = 0;
          resolve(res.data);
        }
        if (res.data.code == 401) {
          if (count > 0) {
            tip.pageDelayJump("../pages/login/phone/phone", null, 1000);
          }
          updateToken();
          globalData.unRequest = function () {
            resolve(self.postJson(url, data))
          }
        }
        resolve(res.data);
      },
      fail: function (res) {
        reject(res.data);
      },
    })
  })
}

export function updateToken() {
  count++;
  let refreshToken = wx.getStorageSync("refreshToken");
  let reflashParams = {
    "refresh_token": refreshToken,
    "grant_type": "refresh_token",
    "scope": "all"
  }
  wx.request({
    url: urls.reflashToken,
    data: reflashParams,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
      'Tenant-Id': '000000'
    },
    method: 'POST',
    success: function (res) {
      if (res.statusCode == 200) {
        setReflashToken(res)
        globalData.unRequest((callback) => {
          callback();
        })
      }
    }
  })
}

function setReflashToken(res) {
  let accessToken = res.data.access_token;
  let refreshToken = res.data.refresh_token;
  wx.setStorageSync("accessToken", accessToken);
  wx.setStorageSync("refreshToken", refreshToken);
}


//获取用户的token，放到请求头中请求数据
export function getToken() {
  let userInfo = wx.getStorageSync("userInfo");
  return "bearer " + userInfo.access_token;
}

// 获取返回的状态值
// true：接口请求成功。有数据
// false：接口请求失败。无数据
export function getReturnData(data) {
  return "200" == data.code ? true : false;
}

// 讲对象数据封装为key=value&key1=value2的字符串
export function getValue(obj) {
  var strs = '';
  for (var str in obj) {
    if (null != obj[str] && "totalPage" != str) {
      strs += str + "=" + obj[str] + "&";
    }
  }
  return strs.substring(0, strs.length - 1);
}

export function splitArr(arr) {
  var obj = {};
  if (null != splitArr) {
    for (var i = 0; i < arr.length; i++) {
      var split = arr[i].split(':');
      obj[split[0]] = split[1];
    }
    return obj;
  }
  return obj;
}

/**
 * 传入时间后几天
 * param：传入时间：dates:"2018-04-02",later:往后多少天
 */
export function dateLater(dates, later) {
  let dateObj = {};
  let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
  let date = new Date(dates);
  date.setDate(date.getDate() + later);
  let day = date.getDay();
  dateObj.year = date.getFullYear();
  dateObj.month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1);
  dateObj.day = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
  dateObj.week = show_day[day];
  //console.info(dateObj)
  return dateObj.year + "-" + dateObj.month + "-" + dateObj.day;
}

//获取px与rpx之间的比列
export function getRpxRate() {
  if (this.rpxRate) {
    return this.rpxRate;
  }
  var winWidth = wx.getSystemInfoSync().windowWidth;
  this.rpxRate = 750 / winWidth;
  return this.rpxRate;
}

export function getPxRate() {
  if (this.pxRate) {
    return this.pxRate;
  }
  var winWidth = wx.getSystemInfoSync().windowWidth;
  this.pxRate = winWidth / 750;
  return this.pxRate;
}

export function isAndroid(app) {
  if (this.isBlank(app.globalData.platform)) {
    return false;
  }
  return 'android' == app.globalData.platform;
}

export function isIOS(app) {
  if (this.isBlank(app.globalData.platform)) {
    return false;
  }
  return 'ios' == app.globalData.platform;
}

export function strLength(str) {
  if (str == undefined || str == null || str == "") {
    return 0;
  }
  var realLength = 0;
  for (var i = 0; i < str.length; ++i) {
    var charCode = str.charCodeAt(i);
    if (charCode >= 0 && charCode <= 128) {
      realLength += 1;
    } else {
      realLength += 2;
    }
  }
  return realLength;
}

export function subFullStr(str, len) {
  if (str == undefined || str == null || str == "") {
    return "";
  }
  var realLen = len;
  if (str.length * 2 <= realLen) {
    return str;
  }
  var realStr = "";
  var realLength = 0;
  for (var i = 0; i < str.length; ++i) {
    var charCode = str.charCodeAt(i);
    if (charCode >= 0 && charCode <= 128) {
      realLength += 1;
    } else {
      realLength += 2;
    }
    // console.log("str", str, "i", i, "sub", str[i], "rl", realLength, "l", realLen)
    if (realLength > realLen) {
      break;
    }
    realStr += str[i];
  }
  return realStr;
}

export function replaceFloat(value) {
  value = value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
  value = value.replace(/^\./g, ""); //验证第一个字符是数字
  value = value.replace(/\.{2,}/g, ""); //只保留第一个, 清除多余的
  value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
  return value;
}

//调用打电话方法
export function callPhone(phone) {
  wx.makePhoneCall({
    phoneNumber: phone
  })
  success: (res) => {
    console.log(res);
  }
  fail: (error) => {
    console.log("取消打电话" + error);
  }
}

//定位(获取当前位置金纬度信息)
export function getLocation(e) {
  //let dataId = e.currentTarget.dataset.id;
  wx.chooseLocation({
    success: function (res) {
      // address: "宁夏回族自治区银川市金凤区良田渠街"
      // errMsg: "chooseLocation:ok"
      // latitude: 38.435947
      // longitude: 106.17504
      // name: "梦驼铃产业平台(银川市金凤区)"
    },
    //错误信息
    fail: function () {
      console.log("定位异常：" + err);
    }
  })
}

// 转换字符串日期时间
export const dateTimeChange = (dateTime, type) => {
  // type不传为 年-月-日 时:分:秒
  // type=1 为 年-月-日
  // type=2 为 时:分:秒
  // type=3 为 年-月-日 时:分
  // type=4 为 月-日 时:分
  // type=5 为 时:分

  // if (dateTime) {
  // if(dateTime.search('-')!=-1){
  //     dateTime=dateTime.replace(/-/, "/")
  // }
  let time = new Date()
  if (dateTime) {
    time = new Date(dateTime)
  }
  const year = time.getFullYear()
  let month = time.getMonth() + 1
  let date = time.getDate()
  const Time = time.toTimeString().slice(0, 8)
  const Time1 = time.toTimeString().slice(0, 5)
  month <= 9 ? month = '0' + month : month
  date <= 9 ? date = '0' + date : date
  if (type === 1) {
    return year + '-' + month + '-' + date
  } else if (type === 2) {
    return Time
  } else if (type === 3) {
    return year + '年' + month + '月' + date + '日 ' + Time1
  } else if (type === 4) {
    return month + '月' + date + '日 ' + Time1
  } else if (type === 5) {
    return month + '月' + date + '日'
  } else if (type === 6) {
    return Time1
  } else if (type === 7) {
    return year + '/' + month + '/' + date
  } else if (type === 8) {
    return year + '年' + month + '月' + date + '日 '
  } else {
    return year + '-' + month + '-' + date + ' ' + Time
  }
  // } else {
  //     return '日期格式有误'
  // }
}

export function getFont(data, key, fieldKey, fieldFont) {
  if (!fieldKey) {
    fieldKey = "dictKey"
  }
  if (!fieldFont) {
    fieldFont = "dictValue"
  }
  // console.log(data,'data')
  // console.log(key,'key')
  // console.log(fieldKey,'fieldKey')
  // console.log(fieldFont,'fieldFont')
  let font = ""
  data.forEach((item) => {
    if (key == item[fieldKey]) {
      font = item[fieldFont]
    }
  });
  return font
}

export function NumberAdd(arg1, arg2) {
  var r1, r2, m, n;
  try {
    r1 = arg1.toString().split(".")[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split(".")[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2))
  n = (r1 >= r2) ? r1 : r2;
  return ((arg1 * m + arg2 * m) / m).toFixed(n);
}

export function NumberSub(arg1, arg2) {
  var re1, re2, m, n;
  try {
    re1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    re1 = 0;
  }
  try {
    re2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    re2 = 0;
  }
  m = Math.pow(10, Math.max(re1, re2));
  n = (re1 >= re2) ? re1 : re2;
  return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
//经营看板数量
export function lineDataFrom(url, data) {
  return new Promise(function (resolve, reject) {
    console.log(url)
    wx.request({
      url: url,
      data: data,
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
        'Blade-Auth': getToken()
      },
      success: function (res) {
        if (res.data.code == 200) {
          count = 0;
          resolve(res.data);
        }
        if (res.data.code == 401) {
          if (count > 0) {
            tip.pageDelayJump("../pages/login/phone/phone", null, 1000);
          }
          // updateToken();
          // globalData.unRequest = function () {
          //   resolve(self.postJson(url, data))
          // }
        }
        resolve(res.data);
      },
      fail: function (res) {
        reject(res.data);
      },
    })
  })
}